package com.apexedu.biz.controller;

import com.alibaba.fastjson.JSON;
import com.apexedu.biz.UrlsConst;
import com.apexedu.biz.entity.client.CommandResult;
import com.apexedu.biz.service.impl.RegulationServiceImpl;
import com.apexedu.cms.CmsEnum;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 规则中心
 * User: 杨建亮
 * Date: 13-12-13  下午2:41
 */
@Controller
public class RegulationController {

    private static final Log LOG = LogFactory.getLog(RegulationController.class);

    @Resource(name="regulationService")
    RegulationServiceImpl regulationService;

    /**
     * 根据资源编号获取规则信息的API
     * @param srcId 客户端的资源编号（对应bizcode）
     * @return
     */
    @RequestMapping(value = UrlsConst.GET_RULES, method = RequestMethod.GET)
    public @ResponseBody
    String getRules(@PathVariable String srcId, HttpServletRequest request) {
        CommandResult result;
        String clientAppId = request.getHeader("AuC"); // 客户端接入号
        String basePath =  request.getScheme()+"://"+request.getServerName()+":"+ request.getServerPort() + request.getContextPath();
        try {
            result = regulationService.getRules(basePath, clientAppId, srcId);
        } catch (Exception e) {
            LOG.error(e);
            result = new CommandResult();
            result.setHasError(true); // 默认是false
            result.setError( e.getMessage() );
        }
        return JSON.toJSONString(result); // 客户端也使用 fastJson 转换
    }

    /**
     * 获取指定用户的所有资源。由规则中心平台提供展示效果页面。
     * @param gzwid 规则WID
     * @return
     */
    @RequestMapping(value = UrlsConst.RULES_DETAIL, method = RequestMethod.GET)
    public String rulesDetail( @PathVariable String gzwid, ModelMap model) {
        try {
            regulationService.rulesDetail(gzwid,model);
        } catch (Exception e) {
            LOG.error(e);
            model.addAttribute(CmsEnum.AppError.toString(), e);
        }
        return "business/regulation/detail.jsp";
    }

}
